using System.Collections.Generic;
using System.Collections;
using UnityEngine.UI;
using System.Linq;
using UnityEngine;
using System.Threading.Tasks;
using System.Diagnostics;
using Debug = UnityEngine.Debug;


public class UIManager : MonoSingleton<UIManager>
{
    private const string UI_Prefab_Default_Path = "Perfab/UI/";
    
    [SerializeField] public Canvas UICanvas;
    [SerializeField] public RectTransform CanvasRect;

    [SerializeField] public RectTransform WinRoot;
    [SerializeField] public RectTransform FuncRoot;
    [SerializeField] public RectTransform PopRoot;
    [SerializeField] public RectTransform TipsRoot;
    [SerializeField] public RectTransform MaskRoot;
    [SerializeField] public RectTransform GuideRoot;
    
    private List<string> PreOpenWindows = new List<string>();
    private List<string> PreOpenWindowPops = new List<string>();
    private List<BaseView> UIList = new List<BaseView>();

    
    private GameObject Mask;				//ui遮罩

    protected override void Awake()
    {
        UICanvas = GameObject.Find("Canvas").GetComponent<Canvas>();
        CanvasRect = UICanvas.GetComponent<RectTransform>();

        WinRoot = GameObject.Find("UIRoot/WinRoot").GetComponent<RectTransform>();
        PopRoot = GameObject.Find("UIRoot/PopRoot").GetComponent<RectTransform>();
        MaskRoot = GameObject.Find("UIRoot/MaskRoot").GetComponent<RectTransform>();
        // TipsRoot = GameObject.Find("UIRoot/TipsRoot").GetComponent<RectTransform>();
        // GuideRoot = GameObject.Find("UIRoot/GuideRoot").GetComponent<RectTransform>();
        // FuncRoot = GameObject.Find("UIRoot/FuncRoot").GetComponent<RectTransform>();
        
        Mask = MaskRoot.Find("Mask").gameObject;
    }
    
    /// <summary>
    /// 设置一层Mask让UI无法点击
    /// </summary>
    /// <param name="show"></param>
    public void ShowMask(bool show)
    {
        Mask.SetActive(show);
    }

    public async Task OpenWindow(string windowName,WindowLayer layer = WindowLayer.Window,params object[] args)
    {
        ShowMask(true);
        if(PreOpenWindows.Contains(windowName))
            Debug.Log($"@mqx 直接打开 {windowName}");
        
        PreOpenWindows.Add(windowName);
        if(layer == WindowLayer.Pop)PreOpenWindowPops.Add(windowName);
        
        GameObject window = null;
        window = AssetManager.Instance.LoadUIPrefab<GameObject>(windowName);
        
        const float checkInterval = 0.01f;
        const float timeout = 3f;
        float waitTime = 0f;
        while(true)
        {
            if(window != null) break;
            waitTime += checkInterval;
            if(waitTime >= timeout)
            {
                ShowMask(false);
                PreOpenWindows.Remove(windowName);
                PreOpenWindowPops.Remove(windowName);
                return;
            }
            await Task.Delay(Mathf.RoundToInt(checkInterval * 1000)); // 转换为毫秒
        }
        ShowMask(false);
        PreOpenWindows.Remove(windowName);
        PreOpenWindowPops.Remove(windowName);

        if(window != null)
        {
            window.name = windowName;
            var baseView = window.GetComponent<BaseView>();
            baseView.SetParams(args);
            baseView.Refresh();
            window.transform.SetParent(GetRoot(layer),false);
            baseView.WindowLayer = layer;
            UIList.Add(baseView); 

        }
        else
        {
            Debug.Log($"@mqx 没有这个界面 {windowName}");
        }
    }
    
    public async void OpenWindowed(string windowName,WindowLayer layer = WindowLayer.Window,params object[] args)
    {
        await OpenWindow(windowName,layer,args);
    }
    
    public RectTransform GetRoot(WindowLayer layer)
    {
        if(layer == WindowLayer.Window)return WinRoot;
        if(layer == WindowLayer.Pop)return PopRoot;
        if(layer == WindowLayer.Mask)return MaskRoot; 
        // if(layer == WindowLayer.Func)return FuncRoot;
        // if(layer == WindowLayer.Guide)return GuideRoot;
        // if(layer == WindowLayer.Tips)return TipsRoot;
        return WinRoot;
    }
    
    /// <summary>
    /// 关闭UI界面
    /// </summary>
    /// <param name="windowName"></param>
    public void CloseWindow(string windowName)
    {
        if(PreOpenWindows.Count > 0)PreOpenWindows.Remove(windowName);
        var index = 0;
        for(int i = UIList.Count - 1;i >= 0; i--)
        {
            var item = UIList[i];
            if(item != null && item.gameObject.name == windowName)
            {
                CloseWindow(item,i,windowName);
                return;
            }
        }
    
    }
    public void CloseWindow(BaseView baseview,int index,string windowName)
    {
        if(baseview != null)
        {
            if(PreOpenWindows.Count > 0)PreOpenWindows.Remove(baseview.gameObject.name);
            GameObject.Destroy(baseview.gameObject);
            UIList.RemoveAt(index);
        }
        
        // JudgeHaveOpenWindow();
        // Utility.SafePostEvent(ConstEvent.RefreshOutLineMask);
        // Utility.SafePostEvent(ConstEvent.WindowClose,windowName);
    }
}